<?php
require_once("header.php");
$pagetitle = "Request A Payment";
$template->assign("pagetitle", $pagetitle);
$template->assign("script", 'cashout');
$template->assign('cashout_available', 0);
$template->assign('QUICK_PAY_AVAILABLE', QUICK_PAY_AVAILABLE);



$template->assign('QUICK_PAY_FEE', (QUICK_PAY_FEE / 100));
$template->assign('QUICK_PAY_FLAT_FEE', QUICK_PAY_FLAT_FEE);

$cd1 = C_DATE1;
$cd2 = C_DATE2;
$dj = date('j');
$template->assign('cdate', 'no');	
if(!empty($cd1))
{
   if(!empty($cd2))
   {
	    if($dj >= $cd1  &&  $dj <= $cd2)
		{
			$template->assign('cdate', 'yes');	
		}
   }else
   {
	   if($dj == $cd1)   
	   $template->assign('cdate', 'yes');		   
   }	
}else
{
	$template->assign('cdate', 'yes');	
	
}






 $template->assign('C_DATE1', C_DATE1);	
 $template->assign('C_DATE2', C_DATE2);	 


if(!$Auth->checkAuth()) // if user isn't logged in
{
    header("location: index.php");
	exit;
}




$uid = $Auth->getLoggedId();
$method = '';
$min_quick_payment = '25'; //Minimum value for quick payment.


if(isset($_SESSION['pay_success']))
{
    $template->assign('success_msg', $_SESSION['pay_success']);	
	$_SESSION['pay_success'] = null;
	unset($_SESSION['pay_success']);
}




//Get Payment History
$payHistory = getCashoutRequests($uid, 15);
$template->assign('history', $payHistory);


$priority = 'normal';



$pendingRequests = 'no';			
if(mysql_num_rows(mysql_query("SELECT * FROM cashouts WHERE uid = '$uloggedId' AND status = 'Pending' AND priority = 'normal'")))
{
	             //now we are allowing multiple cashouts.
                //$pendingRequests = 'yes';
  			    $template->assign('pendingRequests', 0);
}	


if(isset($_POST['cancelCashout']))
{

    $rid = makesafe($_POST['request_id']);
	if(!empty($rid))
	{
		
		$mkq = mysql_query("SELECT amount, fee FROM cashouts WHERE uid = '$uid' AND id = '$rid' AND status = 'Pending' LIMIT 1");
		if(mysql_num_rows($mkq)){
			
		  $mkr = mysql_fetch_object($mkq);	
		  $amount = stripslashes($mkr->amount);
		  $fee = $mkr->fee;
		  
		  if(mysql_query("DELETE FROM cashouts WHERE uid = '$uid' AND id = '$rid' AND status = 'Pending' LIMIT 1"))
		  {
			  $available_money = Stats::getMoney($Auth->getLoggedId());
			  $updateMoney = Stats::SetMoney($uid, $available_money + $amount + $fee);  // Update new money
			  
			  
			  $template->assign('success_msg', 'Your cashout request has been cancelled successfully.');

  
			  //Get Payment History
			  $payHistory = getCashoutRequests($uid, 15);
			  $template->assign('history', $payHistory);
			  $pendingRequests = 'no';			
			  
			  $available_money = Stats::getMoney($Auth->getLoggedId());
			  if($available_money >= MIN_CASHOUT_LIMIT)
			  {
				  $template->assign('cashout_available', 1);
			  }				
              $template->assign('available_money', $available_money);
  			  $template->display('cashout.tpl.php');
			  return;				
		  }else
		  {
			  $error_msg = "An error occured while canceling your cashout request.";
			  $template->assign('error_msg', $error_msg);
			  $template->display('cashout.tpl.php');
			  return;			
		  }
		
		}
	}
	
}elseif(isset($_POST['cashout']))
{
	
	//if(!mysql_num_rows(mysql_query("SELECT * FROM cashouts WHERE uid = '$uid' AND status = 'Pending'"))){
		
	$available_money = Stats::getMoney($Auth->getLoggedId());
	
    $template->assign('available_money', $available_money);
    $money = makesafe($_POST['amount']);
	$method = makesafe($_POST['method']);
	$email = makesafe($_POST['email_address']);
	$notes = makesafe($_POST['notes']);
	$priority = makesafe($_POST['priority']);
	
		
	//check if quick pay is available
	if($priority == 'quick' && QUICK_PAY_AVAILABLE != 1)
	{
	    $error_msg = "Quick payouts are not available.";
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');
		return;		
	}
	
	if($available_money >= MIN_CASHOUT_LIMIT)
	{
		$template->assign('cashout_available', 1);
	}	


 

	//Online payment gateways processing.
	/*if(mysql_num_rows(mysql_query("SELECT * FROM cashouts WHERE uid = '$uid' AND status = 'Pending' AND priority = 'normal'")) && $priority == 'normal'){
		
	    $error_msg = "You already have a pending request for normal payment.";
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');
		return;			
		
	}*/ //We are allowing multiple cashouts now.
	
	if($money < $min_quick_payment && $priority == 'quick')
	{
	    $error_msg = "The minimum amount for early cashout is $min_quick_payment.";
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');
		return;			
	}
	
	

	
	if($priority != 'quick' && $priority != 'normal')
	{
	    $error_msg = "Invalid request priority.";
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');
		return;		
	}
	
	
	
	
	$template->assign('amount', stripslashes($money));
	$template->assign('method', stripslashes($method));
	$template->assign('email', stripslashes($email));
	$template->assign('notes', stripslashes($notes));
	
    
	
    $money = str_replace(',','',$money);
  
	
	if(empty($money) || $money < MIN_CASHOUT_LIMIT)
	{
	    $error_msg = "Empty balance or less then minimum cashout limit.";
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');
		return;
	}
	
	if(empty($method) || ((empty($email) || !validEmail($email)) && ($method != "WesternUnion" && $method != "Wire")))
	{
	    if(empty($method))
		{
		    $error_msg = "Select payment method.";	
		}elseif(empty($email) || !validEmail($email))
		{ 
		    $error_msg = "Enter valid account email address.";	
		}

		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');
		return;	
	} 	
	
	
	if(empty($notes) && ($method == "WesternUnion" || $method == "Wire"))
	{
		$template->assign('error_msg', "Please provide details for your payment transfer");
		$template->display('cashout.tpl.php');
		return;	
		
	}

	
		
	//check if user exists
	$sql = mysql_query("SELECT balance FROM users  WHERE uid = '".$Auth->getLoggedId()."' AND active = 1");
	if(!mysql_num_rows($sql))
	{
	    $error_msg = "Invalid User";
		$template->assign('error_msg', $error_msg);
   		$template->display('cashout.tpl.php');
	    return;
	}
	
	
	
	$row = mysql_fetch_object($sql);
	$user_money = $row->balance;
	
	
	if($money > $user_money) // If user has less money
	{
	    $error_msg = "you dont have that amount you entered.";
		$template->assign('amount', $money);
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');	
		return;	   
	}
	
	
	$user_newmoney = sprintf("%.2f", $user_money - $money); // Deduct money
	$updateMoney = Stats::SetMoney($uid, $user_newmoney);  // Update new money
	

	
	
	if($updateMoney) //If money updated then insert an order into table.
	{
	
	    //deduct fee
		if($priority == 'quick')
		{
			
			//fee calculation
			if(QUICK_PAY_FLAT_FEE > 0){
			$fee =  QUICK_PAY_FLAT_FEE;
			}elseif(QUICK_PAY_FEE > 0)
			{
			   $fee =  sprintf("%.2f", $money*(QUICK_PAY_FEE / 100));				
			}else
			{
				$fee =  0.00;
			}
			
			
			$money = sprintf("%.2f", ($money - $fee));	
			
				
		}else
		{
            $fee = '0.00';			
		}		
	   
	    $new_order = mysql_query("INSERT INTO cashouts(`id`, `uid`,	`amount`, `status`,	`method`, `user_notes`, `admin_notes`, `request_date`, `payment_date`, `email_address`, `priority`,	`fee`) VALUES(NULL, '$uid', '$money', 'Pending', '$method', '$notes', NULL, NOW(), NULL, '$email', '$priority', '$fee')");
		if($new_order)
		{
		
			$available_money = Stats::getMoney($Auth->getLoggedId());
			if($available_money >= MIN_CASHOUT_LIMIT)
			{
				$template->assign('cashout_available', 1);

			}else
			{
				$template->assign('cashout_available', 0);
				
			}
			
		
			//Get Payment History
            $payHistory = getCashoutRequests($uid, 15);
            $template->assign('history', $payHistory);

			$template->assign('pendingRequests', 1);
		    $success_msg = 'Your cashout request has been sent.';
			$_SESSION['pay_success'] = $success_msg;
			header("location: cashout.php");
			exit;
			$template->assign('available_money', $available_money);
		    $template->assign('success_msg', $success_msg);
			
			$template->assign('amount', '');
			$template->assign('method','');
			$template->assign('email', '');
			$template->assign('notes', '');			
			
   			$template->display('cashout.tpl.php');
   			return;
		}else
		{
			$error_msg = "Your cashout request couldn't sent, try later.";
			$template->assign('amount', $money);
			$template->assign('error_msg', $error_msg);
			$template->display('cashout.tpl.php');	
			return;	          
		}
	
	}else
	{
	    $error_msg = "Your cashout request couldn't sent, try later.";
		$template->assign('amount', $money);
		$template->assign('error_msg', $error_msg);
		$template->display('cashout.tpl.php');	
		return;	  		
	}
	
    
	
	


}
    $available_money = Stats::getMoney($Auth->getLoggedId());
	if($available_money >= MIN_CASHOUT_LIMIT)
	{
	    $template->assign('cashout_available', 1);
		
	}
	
	$template->assign('available_money', $available_money);
   	$template->display('cashout.tpl.php');


?>